﻿using Microsoft.Extensions.DependencyInjection;
using SXFramWork.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SXFramWork.Service.CodeGenerratorService
{
    public class CodeGenerratorService:ICodeGenerratorService
    {
        private readonly ILoginInfo _loginInfo;
        private static int dbType = ConfigHelper.app("DBConnection", "Type").To_Int();
        private string conn =dbType==0? ConfigHelper.app("DBConnection", "SqlServer"): ConfigHelper.app("DBConnection", "MySql'");
        private DatabaseType databaseType = dbType==0? DatabaseType.SqlServer:DatabaseType.MySQL;
        public CodeGenerratorService(ILoginInfo loginInfo)
        {
            _loginInfo = loginInfo;           
        }

        public async Task<IApiResult<string>> BuildCode(List<string> tableNames)
        {
            var result = new ApiResult<string>();

            List<DbTable> tables = new List<DbTable>();
            using (var dbConnection = ConnectionFactory.CreateConnection(databaseType, conn))
            {
                tables = dbConnection.GetCurrentDatabaseTableList(DatabaseType.SqlServer);
            }
            var tbs= tableNames;

            List<DbTable> tableToBuild = new List<DbTable>();
            foreach(var item in tbs)
            {
               var tb=tables.Where(a => a.TableName.ToLower()==item.ToLower()).FirstOrDefault();
                tableToBuild.Add(tb);
            }
            //生成代码
            var serviceProvider = ServiceBuilder.BuildServiceForSqlServer(_loginInfo.UserId);
            var codeGenerator = serviceProvider.GetRequiredService<CodeGenerator>();
            codeGenerator.GenerateTemplateCodesFromDatabase(tableToBuild,true,true,true);
            string dirPath = Path.Combine(AppContext.BaseDirectory, "Temp", "BuildCode", _loginInfo.UserId);
            return result.Ok(dirPath);
        }

        public async Task<IApiResult> GetTableColumn(string tableName)
        {
            using (var dbConnection = ConnectionFactory.CreateConnection(databaseType, conn))
            {
                return ApiResult.Ok(dbConnection.GetColumnsByTableName(DatabaseType.SqlServer,tableName.ToLower()));
            }
        }

        public async Task<IApiResult> GetTables()
        {
            //可以list分页
            List<DbTable> tables = new List<DbTable>();
            using (var dbConnection = ConnectionFactory.CreateConnection(databaseType,conn))
            {
                tables = dbConnection.GetCurrentDatabaseAllTables(DatabaseType.SqlServer);
            }
            return ApiResult.Ok(tables);
        }
    }
}
